//
//  TRWeatherViewController.m
//  Weather-UI-V1
//
//  Created by tarena on 15-6-23.
//  Copyright (c) 2015年 tarena. All rights reserved.
//

#import "TRWeatherViewController.h"
#import "TRLabelTool.h"
#import "TRHeadView.h"
#import "TRWeather.h"
#import "AFNetworking.h"
#import "CityMenuController.h"
#import "UIView+Extension.h"
#import "HWDropdownMenu.h"
//#import "MJRefresh.h"



@interface TRWeatherViewController () <UITableViewDataSource, UITableViewDelegate>

//设置私有属性
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *backgroundImageView;

//头部试图
@property (nonatomic, strong)TRHeadView *headView;

//每小时数组
@property (nonatomic, strong) NSArray *hourlyWeather;

//每天数组
@property (nonatomic, strong) NSArray *dailyWeather;

//天气显示的城市
@property(nonatomic,copy)NSString* cityName;
@property (nonatomic, strong) UIRefreshControl* refreshControl;

@end

@implementation TRWeatherViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //初始化tableView
    [self initTableView];
    
    //[self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    //初始化headerView
    [self initHeaderView];
    NSUserDefaults *userDefault  = [NSUserDefaults standardUserDefaults];
    self.cityName = [userDefault objectForKey:@"selectedCity"];
    self.headView.cityLabel.text = [NSString stringWithFormat:@"%@, China",self.cityName];
}

- (void)initHeaderView {
    CGRect headerFrame = [UIScreen mainScreen].bounds;
    
    //TRHeadView: UIView
//    TRHeadView *headView = [[TRHeadView alloc] initWithFrame:headerFrame];
    ///为了显示城市名字
    self.headView = [[TRHeadView alloc] initWithFrame:headerFrame];
    self.headView.backgroundColor = [UIColor clearColor];
    [self.headView.cityBtn addTarget:self action:@selector(cityChanged:) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = self.headView;

    [self addRefresh];
   
    //发送http请求，获取json数据
  
    
    //使用AFNetworking框架
   
}

-(void)cityChanged:(UIButton*)cityBtn{
    // 1.创建下拉菜单
    NSLog(@"%@",@"---------------");
    HWDropdownMenu *menu = [HWDropdownMenu menu];
    
    // 2.设置内容
    CityMenuController *vc = [[CityMenuController alloc] init];
    vc.citySelected = ^(NSString *cityName){
        
        NSLog(@"%@",cityName);
        self.cityName = cityName;
        self.headView.cityLabel.text = [NSString stringWithFormat:@"%@, China",cityName];
        [self sendRequestByAFN:self.refreshControl];
    };
    vc.view.height = 150;
    vc.view.width = 150;
    menu.contentController = vc;
    
    // 3.显示
    [menu showFrom:cityBtn];
    
}

-(void)addRefresh{
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(refreshWeather:) forControlEvents:UIControlEventValueChanged];
    [self.refreshControl setAttributedTitle:[[NSAttributedString alloc] initWithString:@"松手刷新天气"]];
    
    [self.tableView addSubview:self.refreshControl];
    //[self.refreshControl beginRefreshing];
}

-(void)refreshWeather:(UIRefreshControl*)refreshControl{
    [self sendRequestByAFN:refreshControl];
}

-(void)sendRequestByAFN:(UIRefreshControl*)refreshControl {
    
   
    NSURL *weatherURL = [NSURL URLWithString:[ NSString stringWithFormat:@"http://api.worldweatheronline.com/free/v2/weather.ashx?q=%@&num_of_days=4&format=json&tp=3&key=a8c09ec5ab78ed1d0680ad18ac46e", self.cityName]];
    
    // 发送网络请求
    //  1.准备请求
    NSURLRequest *request = [NSURLRequest requestWithURL:weatherURL];
    
    // 2. 使用AFNetworking来解析json请求
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    // 设定解析器
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        //NSLog(@"解析JSON是：%@",responseObject);
        
        //解析json对象
        [self parseJsonData:responseObject];
        
        [refreshControl endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求发送失败：%@",error);
        [refreshControl endRefreshing];
    }];
    
    // 3. 开始任务
    [operation start];
}

- (void)sendRequest {
    
    NSURL *weatherURL = [NSURL URLWithString:[ NSString stringWithFormat:@"http://api.worldweatheronline.com/free/v2/weather.ashx?q=%@&num_of_days=4&format=json&tp=3&key=a8c09ec5ab78ed1d0680ad18ac46e", self.cityName]];
    //NSURL *weatherURL = [NSURL URLWithString:@"http://www.raywenderlich.com/demos/weather_sample/weather.php?format=json"];
    
    //创建请求的对象
    NSURLRequest *request = [NSURLRequest requestWithURL:weatherURL];
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
        
        //服务器返回json数据成功
        if (responseCode == 200) {
            NSLog(@"返回成功: %@", [NSThread currentThread]);
            NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            //解析json对象
            [self parseJsonData:jsonData];
        } else {
            NSLog(@"错误原因是：%@", error.userInfo);
            
        }
    }];
    
    //启动task
    [task resume];
}

//解析json数据
- (void)parseJsonData:(NSDictionary *)jsonData {
    //对象NSDictionary ---> TRWeather
    TRWeather *currentWeather = [TRWeather weatherWithCurrentDic:jsonData];
    
    //解析每小时
    self.hourlyWeather = jsonData[@"data"][@"weather"][0][@"hourly"];
    
    //创建每小时的可变数组
    NSMutableArray *hourlyMutArray = [NSMutableArray new];
    
    for (NSDictionary *hourlyDic in self.hourlyWeather) {
        //对象NSDictionary  ---> TRWeather
        TRWeather *hourlyWeather = [TRWeather weatherWithHourlyDic:hourlyDic];
        
        //添加解析后的TRWeather对象
        [hourlyMutArray addObject:hourlyWeather];
    }
    
    //赋值给小时属性
    self.hourlyWeather = [hourlyMutArray copy];
    
    
    //解析每天
    self.dailyWeather = jsonData[@"data"][@"weather"];
    //创建每天的可变数组
    NSMutableArray *dailyMutArray = [NSMutableArray new];
    
    for (NSDictionary *dailyeDic in self.dailyWeather) {
        //对象NSDictionary  ---> TRWeather
        TRWeather *dailyWeather = [TRWeather weatherWithDailyDic:dailyeDic];
        
        //添加解析后的TRWeather对象
        [dailyMutArray addObject:dailyWeather];
    }
    
    //赋值给天属性
    self.dailyWeather = [dailyMutArray copy];
    

    
    //获取当天最高、最低温度
    float minTemp = currentWeather.minTemp;
    float maxTemp = currentWeather.maxTemp;
    
    //gcd队列：串行、并行; global queue; main_queue
    //发送方式：sync; async
    
    //回到主线程更新ui控件
    dispatch_async(dispatch_get_main_queue(), ^{
        //城市名字
        self.headView.cityLabel.text = currentWeather.cityName;
        
        //更新当前温度
        self.headView.tempratureLabel.text = [NSString stringWithFormat:@"%.0f°", currentWeather.tempC];
        
        //显示最高、最低温度
        self.headView.hiloLabel.text = [NSString stringWithFormat:@"%.0f° / %.0f°", minTemp, maxTemp];
        
        //显示天气描述
        self.headView.conditionLabel.text = currentWeather.weatherDesc;
        
        //显示图标
//        self.headView.iconView.image = [UIImage imageWithData:iconData];
//        NSString *iconUrl = jsonData[@"data"][@"current_condition"][0][@"weatherIconUrl"][0][@"value"];
        self.headView.iconView.image = [UIImage imageNamed:currentWeather.iconName];
        
        //重新刷新table view
        [self.tableView reloadData];
    });
    

}

//手动搭建UI
- (void)initTableView {
    CGRect bounds = self.view.bounds;
    
    //设置背景图片
    self.backgroundImageView = [[UIImageView alloc] initWithFrame:bounds];
    self.backgroundImageView.image = [UIImage imageNamed:@"TomCat.jpg"];
    //加载背景图
    [self.view addSubview:self.backgroundImageView];
    
    //table view创建
    self.tableView = [UITableView new];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.frame = bounds;
    
    //设置dataSource和delegate
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    //设置tableView线的颜色和透明度
    self.tableView.separatorColor = [UIColor colorWithWhite:1 alpha:0.2];
    
    //开启分页功能，将滚动试图UIScrollView分割成独立的段
    self.tableView.pagingEnabled = YES;
    
    //加载tableView
    [self.view addSubview:self.tableView];
    
}

#pragma mark --- dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
    //方法一：
//    if (section == 0) {
//        //第一行被行文本描述占据
//        return self.hourlyWeather.count + 1;
//    } else {
//        return self.dailyWeather.count + 1;
//    }
    //方法二：
    //return section == 0 ? 10: 5;
    return section == 0 ? self.hourlyWeather.count + 1 : self.dailyWeather.count + 1;

    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *CellIdentifier = @"weatherCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    //创建cell
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    
    //设置cell显示
    cell.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    //设置文本颜色
    cell.textLabel.textColor = [UIColor whiteColor];
    //取消选中状态
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    //hourly
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //设置cell文本
            [self configureHeaderCell:cell title:@"Hourly Forecase"];
        } else {
            //非第一行的数据设置
//            NSDictionary *hourlyDic = self.hourlyWeather[indexPath.row - 1];
            TRWeather *hourlyWeatherModel = self.hourlyWeather[indexPath.row - 1];
            [self configureCell:cell weather:hourlyWeatherModel isHourly:YES];
        }
    } else {
        if (indexPath.row == 0) {
            //设置cell文本
            [self configureHeaderCell:cell title:@"Daily Forecase"];
        } else {
            //非第一行的数据设置
//            NSDictionary *dailyDic = self.dailyWeather[indexPath.row - 1];
            TRWeather *dailyWeatherModel = self.dailyWeather[indexPath.row - 1];
            [self configureCell:cell weather:dailyWeatherModel isHourly:NO];
            
        }
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat totalHeight = [UIScreen mainScreen].bounds.size.height;
    
    NSInteger cellCount = [self tableView:tableView numberOfRowsInSection:indexPath.section];
    
    return totalHeight / cellCount;
    
}

#pragma mark --- 配置cell头部
-(void)configureHeaderCell:(UITableViewCell *)cell title:(NSString *)title {
    cell.textLabel.font = [UIFont fontWithName:@"Helveticaneue-Medium" size:18];
    //设置第一行cell文本
    cell.textLabel.text = title;
    cell.detailTextLabel.text = @"Nanjing, China";
    cell.imageView.image = nil;
    
}
             
//配置非第一行数据
//-(void)configureCell:(UITableViewCell *)cell weather:(NSDictionary *)dic isHourly:(BOOL)isHourly {
/////修改成模型类型
-(void)configureCell:(UITableViewCell *)cell weather:(TRWeather *)dic isHourly:(BOOL)isHourly {

    //font
    
//    //显示hourly的time时间
//    NSString *hourlyTime = dic[@"time"];
//    //显示daily的date日期
//    NSString *dailyDate = dic[@"date"];
//    //截断hourly时间:200/800/1400/2000 ---> 2:00/8:00/14:00/20:00
//    //2/8/14/20
//    NSString *hourlyShowTime = [hourlyTime substringToIndex:(hourlyTime.length - 2)];
//    //2:00/8:00/14:00/20:00
    
    
    NSString *finalShowTime = [NSString stringWithFormat:@"%.0f:00", dic.hourly];
    
    //1.hourly/Daily转模型修改的第一个地方
    cell.textLabel.text = isHourly ? finalShowTime : dic.date;
    
    
    //tempC
    //maxtempC/mintempC
    //2.hourly/Daily转模型修改的第二个地方
    NSString *tempC = [NSString stringWithFormat: @"%.0f°", dic.tempC];
    NSString *maxMinTemp = [NSString stringWithFormat:@"%.0f° / %.0f°", dic.maxTemp, dic.minTemp];
    
    
    //3.hourly转模型修改的第三个地方
    cell.detailTextLabel.text = isHourly ? tempC: maxMinTemp;
    
    //显示天气图标
    //imageURL:http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png
    
    //4.hourly转模型修改的第四个地方
//    NSString *imageURL = dic[@"weatherIconUrl"][0][@"value"];
    cell.imageView.image = [UIImage imageNamed:dic.iconName];
}

//#pragma mark --- 图标映射
//- (NSDictionary *)imageMap{
//    
//    return @{
//             [NSString stringWithFormat:@"%@0001_sunny.png",iconURLString]:@"weather-clear.png",
//             [NSString stringWithFormat:@"%@0003_white_cloud.png",iconURLString]:@"weather-few.png",
//             [NSString stringWithFormat:@"%@0004_black_low_cloud.png",iconURLString]:@"weather-scattered.png",
//             [NSString stringWithFormat:@"%@0004_black_low_cloud.png",iconURLString]:@"weather-broken",
//             [NSString stringWithFormat:@"%@0009_light_rain_showers.png",iconURLString]:@"weather-shower",
//             [NSString stringWithFormat:@"%@0025_light_rain_showers_night.png",iconURLString]:@"weather-rain",
//             @"11d":@"weather-tstorm",
//             @"13d":@"weather-snow",
//             [NSString stringWithFormat:@"%@0006_mist.png",iconURLString]
//             :@"weather-mist",
//             [NSString stringWithFormat:@"%@0008_clear_sky_night.png",iconURLString]:@"weather-moon",
//             @"02n":@"weather-few-night",
//             @"03n":@"weather-few-night",
//             [NSString stringWithFormat:@"%@0002_sunny_intervals.png",iconURLString]:@"weather-broken",
//             @"09n":@"weather-shoer",
//             [NSString stringWithFormat:@"%@0025_light_rain_showers_night.png",iconURLString]:@"weather-rain-night",
//             @"11n":@"weather-tstorm",
//             @"13n":@"weather-snow",
//             @"50n":@"weather-mist"
//             };
//}









@end
